#include <Windows.h>
#include <stdio.h>

// 全局变量，用于保存选中的文字
char* g_selectedText = NULL;

// 全局变量，用于保存鼠标按下的位置
POINT g_mouseDownPos;

// 鼠标钩子回调函数
LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION) {
        MOUSEHOOKSTRUCT* mouseData = (MOUSEHOOKSTRUCT*)lParam;
        if (wParam == WM_LBUTTONDOWN) {
            // 记录鼠标按下的位置
            g_mouseDownPos = mouseData->pt;
            // 释放之前的选中文字
            if (g_selectedText != NULL) {
                free(g_selectedText);
                g_selectedText = NULL;
            }
        } else if (wParam == WM_LBUTTONUP) {
            // 记录鼠标弹起的位置
            POINT mouseUpPos = mouseData->pt;
            // 判断鼠标按下和弹起的位置是否相同
            if (mouseUpPos.x != g_mouseDownPos.x || mouseUpPos.y != g_mouseDownPos.y) {
                // 获取选中区域的坐标
                RECT selectedRect;
                selectedRect.left = min(g_mouseDownPos.x, mouseUpPos.x);
                selectedRect.top = min(g_mouseDownPos.y, mouseUpPos.y);
                selectedRect.right = max(g_mouseDownPos.x, mouseUpPos.x);
                selectedRect.bottom = max(g_mouseDownPos.y, mouseUpPos.y);
                // 转换为客户区坐标
                HWND activeWindow = GetForegroundWindow();
                ScreenToClient(activeWindow, (LPPOINT)&selectedRect.left);
                ScreenToClient(activeWindow, (LPPOINT)&selectedRect.right);
                // 获取选中的文字
                HDC hdc = GetDC(activeWindow);
                int bufferSize = GetWindowTextLength(activeWindow) + 1;
                g_selectedText = (char*)malloc(bufferSize * sizeof(char));
                GetClientRect(activeWindow, &selectedRect);
                GetWindowText(activeWindow, g_selectedText, bufferSize);
                ReleaseDC(activeWindow, hdc);
            }
        }
    }
    // 将消息传递给下一个钩子
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int main() {
    // 安装鼠标钩子
    HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE, MouseHookProc, NULL, 0);
    if (mouseHook == NULL) {
        printf("无法安装鼠标钩子\n");
        return 1;
    }
    // 消息循环
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    // 卸载鼠标钩子
    UnhookWindowsHookEx(mouseHook);
    // 打印选中的文字
    if (g_selectedText != NULL) {
        printf("Selected Text: %s\n", g_selectedText);
        free(g_selectedText);
        g_selectedText = NULL;
    }
    return 0;
}